package lib.book;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class updateServlet
 */
@WebServlet("/updateServlet")
public class updateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public updateServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		boolean res=false;
		String str=request.getParameter("txt");
		System.out.println(str);
		if(str.equals("")) {
			bookModule bk=new bookModule();
			bk.setBno(request.getParameter("bno"));
			bk.setTitle(request.getParameter("title"));
			bk.setCategory(request.getParameter("category"));
			bk.setAuthor(request.getParameter("author"));
			bk.setPublish(request.getParameter("publish"));
			bk.setYear(Integer.parseInt(request.getParameter("year")));
			bk.setPrice(Double.parseDouble(request.getParameter("price")));
			bk.setTotal(Integer.parseInt(request.getParameter("total")));
			bk.setStock(Integer.parseInt(request.getParameter("stock")));
			
			bookDao bd=new bookDao();
			try{
				res=bd.insertNew(bk);
				if(res==false) {
					res=bd.updateBook(bk);
				}
				if(res==false) {
					request.getSession().setAttribute("operate_state", 0);
				}
				else {
					request.getSession().setAttribute("operate_state", 1);
				}
				request.getRequestDispatcher("manage.jsp").forward(request, response);
			}catch (Exception e) {
	            e.printStackTrace();
	        }
		}
		else {
			bookDao bd= new bookDao();
			try{
				res=bd.updateMoreBook(request.getParameter("txt"));
				if(res==false) {
					request.getSession().setAttribute("operate_state", 0);
				}
				else {
					request.getSession().setAttribute("operate_state", 1);
				}
				request.getRequestDispatcher("manage.jsp").forward(request, response);
			}catch (Exception e) {
	            e.printStackTrace();
	        }
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
